{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "633bee8b-653c-48e4-a56a-97fee787142b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0., 1., 2., 3.])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#2.5 自动微分\n",
    "# 2.5.1 简单例子\n",
    "import torch\n",
    "x = torch.arange(4.0)\n",
    "x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "eafb2ef9-b579-412e-9aea-c99b334a222b",
   "metadata": {},
   "outputs": [],
   "source": [
    "x.requires_grad_(True) # 等价于x=torch.arange(4.0,requires_grad=True)\n",
    "x.grad"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "4ec5117d-23b4-4533-a0ef-ecbcd25dc1de",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(28., grad_fn=<MulBackward0>)"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 计算y\n",
    "x.grad.zero_()\n",
    "y = 2 * torch.dot(x,x)\n",
    "y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "479d1e8a-d654-4eec-9185-0c0163fafbe7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([ 0.,  4.,  8., 12.])"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#算y关于x每个分量的梯度，并打印这些梯度\n",
    "y.backward()\n",
    "x.grad"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "aaa2aff5-af5c-452c-b515-02e3d8263d84",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([True, True, True, True])"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 验证梯度\n",
    "x.grad == 4*x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "398d0e41-4512-4785-86a0-cc6654e8b345",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0., 2., 4., 6.])"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#2.5.2 非标量变量的反向传播\n",
    "x.grad.zero_()\n",
    "y = x*x\n",
    "y.sum().backward()\n",
    "x.grad"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "281dbfcb-97ef-4a93-a343-bab698921e3f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([True, True, True, True])"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#2.5.3. 分离计算\n",
    "x.grad.zero_()\n",
    "y = x* x\n",
    "u = y.detach()\n",
    "z = u * x\n",
    "\n",
    "z.sum().backward()\n",
    "x.grad == u"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "a91c7dfd-c8c7-4679-9928-b107a8d3c615",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([True, True, True, True])"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.grad.zero_()\n",
    "y.sum().backward()\n",
    "x.grad == 2*x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "5438f5b3-2fa9-4b51-af3c-ae5965e0863b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2.5.4 Python控制流的梯度计算\n",
    "def f(a):\n",
    "    b = a * 2\n",
    "    while b.norm() < 1000:\n",
    "        b = b * 2\n",
    "    if b.sum() > 0:\n",
    "        c = b\n",
    "    else:\n",
    "        c = 100 * b\n",
    "    return c\n",
    "\n",
    "a = torch.randn(size=(),requires_grad= True)\n",
    "d = f(a)\n",
    "d.backward()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "63ecdd0d-53b4-477f-8000-9696abda22b8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(True)"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.grad == d/a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "3ddf062c-e3ac-4ea2-b1f8-57bff264d45a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(0.2148, requires_grad=True)"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ce54c41-840d-42d0-9825-1b5872ac53bf",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
